<template>
  <div class="app-container">
    <!-- 查询条件区域 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="聚合步长">
              <el-select v-model="queryParams.step" placeholder="请选择聚合步长" clearable>
                <el-option v-for="item in stepOptions" :key="item.dictValue" :label="item.dictLabel" 
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="监测项">
              <el-select v-model="queryParams.metricTypeId" placeholder="请选择监测项" clearable 
                @change="handleMetricChange">
                <el-option v-for="item in metricOptions" :key="item.dictValue" :label="item.dictLabel" 
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="监测点">
              <el-select v-model="queryParams.monitorCodes" multiple placeholder="请选择监测点" clearable 
                style="width: 100%">
                <el-option v-for="item in monitorOptions" :key="item.dictValue" :label="item.dictLabel" 
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="时间范围">
              <el-date-picker v-model="queryParams.timeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="text-align: left;">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <el-card class="mt-2">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="实时曲线" name="chart">
          <div>
            <ChartComponent :option="chartOption" :style="{ height: '400px' }" />
          </div>
        </el-tab-pane>
        <el-tab-pane label="最新数据" name="table">
          <el-table :data="latestData" border v-loading="tableLoading" class="mt-2">
            <el-table-column prop="monitorName" label="监测点名称" align="center" />
            <el-table-column prop="value" label="最新值" align="center">
              <template #default="{ row }">
                <span :class="getValueClass(row.status)">
                  {{ row.value?.toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="updatedAt" label="更新时间" align="center" />
            <el-table-column prop="status" label="状态" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)">
                  {{ getStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import ChartComponent from '@/components/ECharts'

// API接口
import {
  getStepOptions,
  getMetricOptions,
  getMonitorOptions,
  getRealtimeSeries,
  getRealtimeLatest
} from '@/api/dispatch/detection/real_time_data'

// 查询参数
const queryParams = reactive({
  step: '5m',
  metricTypeId: '',
  monitorCodes: [],
  timeRange: []
})

// 下拉选项数据
const stepOptions = ref([])
const metricOptions = ref([])
const monitorOptions = ref([])

// 图表和数据
const chartOption = ref({})
const latestData = ref([])
const activeTab = ref('chart')

// 加载状态
const tableLoading = ref(false)
const chartLoading = ref(false)

// 获取步长选项
const fetchStepOptions = async () => {
  try {
    const res = await getStepOptions()
    stepOptions.value = res.data || []
  } catch (error) {
    console.error('获取步长选项失败:', error)
    ElMessage.error('获取步长选项失败')
  }
}

// 获取监测项选项
const fetchMetricOptions = async () => {
  try {
    const res = await getMetricOptions()
    metricOptions.value = res.data || []
  } catch (error) {
    console.error('获取监测项选项失败:', error)
    ElMessage.error('获取监测项选项失败')
  }
}

// 获取监测点选项
const fetchMonitorOptions = async () => {
  try {
    if (!queryParams.metricTypeId) {
      monitorOptions.value = []
      return
    }
    
    const res = await getMonitorOptions({
      metricTypeId: queryParams.metricTypeId
    })
    monitorOptions.value = res.data || []
  } catch (error) {
    console.error('获取监测点选项失败:', error)
    ElMessage.error('获取监测点选项失败')
  }
}

// 监测项变化处理
const handleMetricChange = () => {
  queryParams.monitorCodes = []
  fetchMonitorOptions()
}

// 获取实时曲线数据
const fetchRealtimeSeries = async () => {
  try {
    chartLoading.value = true
    
    if (!queryParams.metricTypeId || queryParams.monitorCodes.length === 0) {
      ElMessage.warning('请选择监测项和监测点')
      return
    }

    if (!queryParams.timeRange || queryParams.timeRange.length !== 2) {
      ElMessage.warning('请选择时间范围')
      return
    }

    const res = await getRealtimeSeries({
      monitorCodes: queryParams.monitorCodes,
      start: queryParams.timeRange[0],
      end: queryParams.timeRange[1],
      step: queryParams.step
    })
    generateChartOption(res.data || [])
  } catch (error) {
    console.error('获取实时曲线数据失败:', error)
    ElMessage.error('获取实时曲线数据失败')
  } finally {
    chartLoading.value = false
  }
}

// 获取最新数据
const fetchLatestData = async () => {
  try {
    tableLoading.value = true
    
    if (!queryParams.metricTypeId || queryParams.monitorCodes.length === 0) {
      ElMessage.warning('请选择监测项和监测点')
      return
    }

    const res = await getRealtimeLatest({
      monitorCodes: queryParams.monitorCodes,
      start: queryParams.timeRange?.[0] || '',
      end: queryParams.timeRange?.[1] || '',
      step: queryParams.step
    })
    latestData.value = res.data || []
  } catch (error) {
    console.error('获取最新数据失败:', error)
    ElMessage.error('获取最新数据失败')
  } finally {
    tableLoading.value = false
  }
}

// 生成图表配置
const generateChartOption = (seriesData) => {
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
  
  const series = seriesData.map((item, index) => ({
    name: item.monitorName,
    type: 'line',
    data: item.points?.map(point => [new Date(point.ts).getTime(), point.value]) || [],
    symbol: 'circle',
    symbolSize: 4,
    lineStyle: {
      width: 2
    },
    itemStyle: {
      color: colors[index % colors.length]
    }
  }))

  chartOption.value = {
    title: {
      text: '实时数据对比曲线',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `${params[0].axisValueLabel}<br/>`
        params.forEach(param => {
          result += `${param.seriesName}: ${param.value[1]?.toFixed(2)}<br/>`
        })
        return result
      }
    },
    legend: {
      data: seriesData.map(item => item.monitorName),
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'time',
      axisLabel: {
        formatter: function (value) {
          return new Date(value).toLocaleString()
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: series,
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 0,
        end: 100
      },
      {
        type: 'slider',
        xAxisIndex: [0],
        start: 0,
        end: 100
      }
    ]
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  const map = {
    '正常': 'success',
    '异常': 'danger',
    '缺失': 'warning'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  return status || '未知'
}

// 获取数值样式类
const getValueClass = (status) => {
  const map = {
    '正常': 'value-normal',
    '异常': 'value-abnormal',
    '缺失': 'value-missing'
  }
  return map[status] || 'value-unknown'
}

// 查询按钮
const handleQuery = () => {
  if (activeTab.value === 'chart') {
    fetchRealtimeSeries()
  } else {
    fetchLatestData()
  }
}

// 重置查询
const resetQuery = () => {
  queryParams.step = '5m'
  queryParams.metricTypeId = ''
  queryParams.monitorCodes = []
  queryParams.timeRange = []
  
  chartOption.value = {}
  latestData.value = []
}

// 标签页切换
const handleTabChange = (tabName) => {
  activeTab.value = tabName
  if (queryParams.metricTypeId && queryParams.monitorCodes.length > 0) {
    handleQuery()
  }
}

// 初始化加载数据
onMounted(() => {
  fetchStepOptions()
  fetchMetricOptions()
  
  // 设置默认时间范围（最近24小时）
  const end = new Date()
  const start = new Date(end.getTime() - 24 * 60 * 60 * 1000)
  queryParams.timeRange = [
    start.toISOString().replace('T', ' ').substring(0, 19),
    end.toISOString().replace('T', ' ').substring(0, 19)
  ]
})
</script>

<style scoped>

</style>